#include <iostream>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include "netctl.h"
#include "DataFrame.h"
#include <dirent.h>
#include "ConfigReader.h"
#include "NodeHandler.h"
#include "net_tool.h"
#include "http.h"
#include "http-config.h"
// HTTP服务连接接受线程
void * http_accept_thread(void * arg) {
    int* socket_fd = (int*)arg;
    pthread_t pid;
    socketinf *inf;
    while (1) {
        inf = (socketinf*)malloc(sizeof(socketinf));
        try {
            *inf = Accept(*socket_fd);
            pthread_create(&pid, NULL, http_portal, inf);
            pthread_detach(pid);
        } catch(const Exception& e) {
            std::cerr << "HTTP accept failed: ";
            std::cerr << e.what() << '\n';
        }
        
    }
    free(socket_fd);
    return nullptr;
}

// HTTP服务请求处理线程
void * http_portal(void * arg) {
    socketinf * inf = (socketinf*)arg;
    HttpRequest request(*inf);
    HttpResponse response(*inf);
    try {
        std::string uri = request.getURI();
        WebRouteMapper::getController(uri)
                        ->service(request, response);
    } catch (const std::exception& e) {
        std::string content = e.what();
        response.setContentType("text/html;charset=utf-8")
                .setContentLength(content.length())
                .setStatus(500, "Server Error")
                .write(content);
        std::cerr << e.what() << '\n';
    }
    close(inf->socket_fd);
    free(arg);
    return nullptr;
}

// Core服务连接接受线程
void * core_accept_thread(void * arg) {
    int* socket_fd = (int*)arg;
    pthread_t pid;
    socketinf *inf;
    while (1) {
        inf = (socketinf*)malloc(sizeof(socketinf));
        try {
            *inf = Accept(*socket_fd);
            pthread_create(&pid, NULL, core_portal, inf);
            pthread_detach(pid);
        } catch(const Exception& e) {
            std::cerr << "Core service accept failed: ";
            std::cerr << e.what() << '\n';
        }
    }
    free(socket_fd);
    return nullptr;
}

// Core服务请求处理线程
void * core_portal(void * arg) {
    socketinf * inf = (socketinf*)arg;
    std::string list;
    DataFrame dataFrame;
    int ret = AUTO_CLOSE;
    try {
        do
        {
            dataFrame.readFrame(inf->socket_fd);
            ret = nodeHandler.getClientTaskExecutor(dataFrame.flag)
            ->serverAction(*inf, dataFrame.length);
        } while (ret == CONTINUE);
    } catch(const Exception &e) {
        std::cerr << e.what() << std::endl;
        ret = AUTO_CLOSE;
    }

    // 由核心处理线程释放socket连接
    if (ret == AUTO_CLOSE) {
        inf->close();
    }
    free(arg);
    return nullptr;
}